package com.xiaomaoguai.fcp.pre.kepler.oss.configuration;

import com.xiaomaoguai.fcp.pre.kepler.oss.constants.OssConstants;
import com.xiaomaoguai.fcp.pre.kepler.oss.utils.OssClient;
import com.xiaomaoguai.fcp.pre.kepler.oss.utils.OssClientUtils;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.Objects;

/**
 * @author WeiHui
 * @date 2019/3/20 19:05
 * @since JDK 1.8
 */
@Slf4j
public class MultiOssScannerConfigurer implements BeanDefinitionRegistryPostProcessor, InitializingBean, ApplicationContextAware, BeanNameAware {

	private ApplicationContext applicationContext;

	@Setter
	private MultiOssProperties multiOssProperties;

	@Override
	public void setBeanName(String name) {
		log.info("init bean {}", name);
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		Objects.requireNonNull(this.multiOssProperties, "multiOssProperties不能为空");
		Objects.requireNonNull(this.applicationContext, "applicationContext不能为空");
	}

	@Override
	public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException {
		String beanSuffixName = StringUtils.capitalize(OssConstants.BEAN_SUFFIX_NAME);
		multiOssProperties.getClients().forEach((productCode, ossProperties) -> {
			AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition(OssClient.class,
					() -> OssClientUtils.buildOssClient(ossProperties))
					.getRawBeanDefinition();
			beanDefinition.setInitMethodName("init");
			beanDefinition.setDestroyMethodName("shutDown");
			beanDefinitionRegistry.registerBeanDefinition(productCode + beanSuffixName, beanDefinition);
		});
	}

	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {

	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}

}
